/* 使用promise对象 实现请求解决回调地狱 */

function request(url, method = "GET", data = {}, header = {}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header,
      success: (res) => {
        resolve(res)
      }
    })
  })
}
//为请求函数设置基准路径
const baseUrl = 'https://autumnfish.cn/wx/api/public/v1/';
//为get请求而活
request.get = function (url, data) {
  //在这将我的数据发送给我的request请求函数
  //我们需要将我们的函数返回 因为request返回一个promise对象 我们get也需要
  return request(baseUrl + url, 'GET', data)
}
//post请求
request.post = function (url, data) {
  return request(baseUrl + url, 'POST', data)
}
//用户授权
request.auth = function (url, data) {
  const token = wx.getStorageSync('token');
  if (token) {
    return request(baseUrl + url, 'POST', data, {
      "Authorization": token
    })
  } else {
    wx.navigateTo({
      url: '/pages/auth/main'
    });
    return new Promise(() => {})
  }
}
//get
request.auth.get = function (url, data) {
  const token = wx.getStorageSync('carts');
  if (token) {
    return request(baseUrl + url, 'GET', data, {
      "Authorization": token
    })
  } else {
    wx.navigateTo({
      url: '/pages/auth/main'
    });
    return new Promise(() => {})
  }
}
//导出
export default request
